package com.xujl.hsns.server;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 class ServicesClip {
	 private final static Logger LOGGER = LoggerFactory.getLogger(ServicesClip.class);
	private Map  SERVICES  =   Collections.synchronizedMap( new HashMap());
	private List  SERVICESCLASSES  =   (new ArrayList());
	
	
	
	/**
	 * 
	 * @param Interfaceclazz 
	 * @param impl
	 */
	public void addService(Class Interfaceclazz,Object impl) throws Exception{
		Interfaceclazz.cast(impl);
		SERVICESCLASSES.add(Interfaceclazz.toString());
		collectServiceMethod( Interfaceclazz, impl);
	}
	Object invoke(String genericString,Object[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		ImplPacking packing = (ImplPacking)SERVICES.get(genericString);
		LOGGER.debug(packing.method.toGenericString());
		Object invoke = packing.method.invoke(packing.impl, args);
		LOGGER.debug(packing.method.toGenericString()+"ok");
		
		return invoke;
	}
	
	public List getServices(){
		return SERVICESCLASSES;
	}
	public List getServiceMethods(){
		return new ArrayList(SERVICES.keySet());
	}
	private void collectServiceMethod(Class interfaceclazz, Object impl) throws Exception {
		Method[] declaredMethods = interfaceclazz.getDeclaredMethods();
		
		for (int i = 0; i < declaredMethods.length; i++) {
			Method imethod=declaredMethods[i];
			Method method = impl.getClass().getDeclaredMethod(imethod.getName(), imethod.getParameterTypes());
			SERVICES.put(imethod.toGenericString(),ImplPacking.create(impl, method));
		}
		
	}
}
